﻿using System;
using System.Collections.Generic;
using System.Data.Entity.SqlServer;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Admin.Models;
using Admin.Models.BlackList;
using Admin.Models.Chart;
using Admin.Models.Report;
using OutDbContext;
using Admin.Helpers;
using MySql.Data.MySqlClient;

namespace Admin.Controllers
{

    public partial class GridController : Controller
    {
        private GdsfybjyWeiXinEntities _ctx;

        protected override void Initialize(RequestContext requestContext)
        {
            _ctx = new GdsfybjyWeiXinEntities();
            base.Initialize(requestContext);
        }

        protected override void Dispose(bool disposing)
        {
            _ctx.Dispose();
            base.Dispose(disposing);
        }

        #region 科室管理
        public ActionResult Departs_Read([DataSourceRequest]DataSourceRequest request)
		{
			var result = _ctx.Departs
                .Select(x => new DepartViewModel
            {
				Id = x.Id,
                DepartName = x.DeptName,
                DepartNo = x.DeptId,
                Loc = x.Loc,
                IsShow = x.RecStatus,
                SortNo = x.Sort,
                CreateTime = x.RecCreateDt,
                ModifiedTime = x.RecUpdateDt,
                Desc = x.Desc
			});

			return Json(result.ToDataSourceResult(request));
		}

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Depart_Create([DataSourceRequest] DataSourceRequest request, DepartViewModel depart)
        {
            if (depart != null && ModelState.IsValid)
            {
                Depart dbDepart = new Depart
                {
                    Desc = depart.Desc,
                    DeptName = depart.DepartName,
                    Loc = depart.Loc,
                    Sort = depart.SortNo,
                    RecStatus = 1
                };
                _ctx.Departs.Add(dbDepart);
                _ctx.SaveChanges();

            }

            return Json(new[] { depart }.ToDataSourceResult(request, ModelState));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Depart_Update([DataSourceRequest] DataSourceRequest request, DepartViewModel depart)
        {
            if (depart != null && ModelState.IsValid)
            {
                var dbDepart = _ctx.Departs.FirstOrDefault(x => x.Id == depart.Id);
                if (dbDepart != null)
                {
                    dbDepart.Desc = depart.Desc;
                    dbDepart.DeptName = depart.DepartName;
                    dbDepart.Loc = depart.Loc;
                    dbDepart.Sort = depart.SortNo;
                    dbDepart.RecStatus = depart.IsShow == 1 ? 1 : 2;
                    _ctx.SaveChanges();
                }
            }

            return Json(new[] { depart }.ToDataSourceResult(request, ModelState));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Depart_Destroy([DataSourceRequest] DataSourceRequest request, DepartViewModel depart)
        {
            if (depart != null)
            {
                var dbDepart = _ctx.Departs.FirstOrDefault(x => x.Id == depart.Id);
                if (dbDepart != null)
                {
                    dbDepart.RecStatus = 2;
                    dbDepart.RecDeleteDt = DateTime.Now;

                    _ctx.SaveChanges();
                }
            }

            return Json(new[] { depart }.ToDataSourceResult(request, ModelState));
        }
        #endregion

        #region 医生管理

        public ActionResult Doctors_Read([DataSourceRequest] DataSourceRequest request)
        {
            var result = _ctx.Doctors.Select(x => new DoctorViewModel
            {
                Id = x.Id,
                DepartName = x.DepartName,
                DoctorName = x.DoctorName,
                DoctortNo = x.DoctorId,
                IsShow = x.RecStatus,
                SortNo = x.Sort,
                CreateTime = x.RecCreateDt,
                ModifiedTime = x.RecUpdateDt,
                Desc = x.Desc,
                Title = x.Title,
                Gender = x.Gender,
                TitleImg = x.TitleImg
            });

            return Json(result.ToDataSourceResult(request));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Doctor_Create([DataSourceRequest] DataSourceRequest request, DoctorViewModel doctor)
        {
            if (doctor != null && ModelState.IsValid)
            {
                Doctor dbDoctor = new Doctor
                {
                    Desc = doctor.Desc,
                    DoctorName = doctor.DoctorName,
                    Title = doctor.Title,
                    Gender = doctor.Gender,
                    TitleImg = doctor.TitleImg,
                    Sort = doctor.SortNo,
                    RecStatus = 1
                };
                _ctx.Doctors.Add(dbDoctor);
                _ctx.SaveChanges();
            }

            return Json(new[] {doctor}.ToDataSourceResult(request, ModelState));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Doctor_Update([DataSourceRequest] DataSourceRequest request, DoctorViewModel doctor)
        {
            if (doctor != null && ModelState.IsValid)
            {
                var dbDoctor = _ctx.Doctors.FirstOrDefault(x => x.Id == doctor.Id);
                if (dbDoctor != null)
                {
                    dbDoctor.Desc = doctor.Desc;
                    dbDoctor.DoctorName = doctor.DoctorName;
                    dbDoctor.Title = doctor.Title;
                    dbDoctor.Gender = doctor.Gender;
                    dbDoctor.TitleImg = doctor.TitleImg;
                    dbDoctor.Sort = doctor.SortNo;
                    dbDoctor.RecStatus = doctor.IsShow == 1 ? 1 :2;
                    dbDoctor.RecUpdateDt = DateTime.Now;
                  
                    _ctx.SaveChanges();
                }
            }


            return Json(new[] {doctor}.ToDataSourceResult(request, ModelState));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Doctor_Destroy([DataSourceRequest] DataSourceRequest request, DoctorViewModel doctor)
        {
            if (doctor != null)
            {
                var dbDoctor = _ctx.Doctors.FirstOrDefault(x => x.Id == doctor.Id);
                if (dbDoctor != null)
                {
                    dbDoctor.RecStatus = 2;
                    dbDoctor.RecDeleteDt = DateTime.Now;

                    _ctx.SaveChanges();
                }
            }

            return Json(new[] {doctor}.ToDataSourceResult(request, ModelState));
        }

        #endregion

        #region 报表
        public ActionResult Appts_Read([DataSourceRequest]DataSourceRequest request)
        {
            var result = _ctx.ApptOrders
                .Select(x => new ApptViewModel
                {
                    Id = x.Id,
                    CardNo = x.CardNo,
                    RegDate = x.RegDate,
                    OrderNo = x.OrderNo,
                    StartTime = x.StartTime,
                    EndTime = x.EndTime,
                    PayState = x.PayState,
                    Fee = x.Fee,
                    TreatFee = x.TreatFee,
                    SumFee = x.SumFee,
                    WxTranscationId = x.WxTransactionId,
                    CreatedTime = x.CreateTime,
                    PayTime = x.PayTime
                });

            return Json(result.ToDataSourceResult(request));
        }

        public ActionResult Dinners_Read([DataSourceRequest]DataSourceRequest request)
        {
            var result = from x in _ctx.DinnerOrders
                join b in _ctx.DinnerBills
                    on x.BillId equals b.Id
                select new DinnerViewModel
                {
                    Id = x.Id,
                    CardNo = x.CardNo,
                    OrderNo = x.OrderNo,
                    FpName = x.FpName,
                    HmtName = x.HmtName,
                    Fee = x.FoodAmount,
                    PayState = x.PayStatus,
                    WxTranscationId = b.WxTransactionId,
                    DcBillNo = x.DcBillNo,
                    DinnerDate = x.DinnerDate,
                    CreatedTime = x.CreateTime,
                    PayTime = x.PayTime,
                };

            return Json(result.ToDataSourceResult(request));
        }

        public ActionResult Bills_Read([DataSourceRequest]DataSourceRequest request)
        {
            var result = _ctx.BillOrders
                .Select(x => new BillViewModel
                {
                    Id = x.Id,
                    CardNo = x.CardNo,
                    OrderNo = x.OrderNo,
                    ClinicNo = x.ClinicNo,
                    Remark = x.Remark,
                    Fee = x.PrescMoney,
                    PayState = x.PayState,
                    WxTranscationId = x.WxTransactionId,
                    CreatedTime = x.CreateTime,
                    PayTime = x.PayTime
                });

            return Json(result.ToDataSourceResult(request));
        }

        public ActionResult Prepays_Read([DataSourceRequest]DataSourceRequest request)
        {
            var result = _ctx.InpatientPrepayOrders
                .Select(x => new PrepayViewModel()
                {
                    Id = x.Id,
                    CardNo = x.CardNo,
                    OrderNo = x.OrderNo,
                    Remark = x.Remark,
                    Fee = x.PrepayMoney,
                    PayState = x.PayState,
                    WxTranscationId = x.WxTransactionId,
                    CreatedTime = x.CreateTime,
                    PayTime = x.PayTime,
                    RefundTime = x.RefundTime,
                    WxRefundId = x.WxRefundId
                });

            return Json(result.ToDataSourceResult(request));
        }
        #endregion

        #region 黑名单管理
        public ActionResult BlackLists_Read([DataSourceRequest]DataSourceRequest request)
        {
            var result = _ctx.WxBlackLists
                .Select(x => new 
                {
                    Id = x.Id,
                    CardType = x.CardType,
                    CardNo = x.CardNo,
                    PatientName = x.PatientName,
                    CancelCount = x.CancelCount,
                    CancelMonth = x.CancelMonth,
                    CancelYear = x.CancelYear,
                    IdenNo = x.IdenNo,
                    Phone = x.Phone
                });

            return Json(result.ToDataSourceResult(request, x => new BlackListViewModel
            {
                Id = x.Id,
                CardType = GetCardType(x.CardType),
                CardNo = x.CardNo,
                PatientName = x.PatientName,
                CancelCount = x.CancelCount,
                CancelMonth = x.CancelMonth,
                CancelYear = x.CancelYear,
                IdenNo = x.IdenNo,
                Phone = x.Phone
            }));
        }

        private CardType GetCardType(int? cardTypeValue)
        {
            int cardType = cardTypeValue ?? -1;
            CardType _cardType = new CardType() {Id = cardType};
            switch (cardType)
            {
                case 0:
                    _cardType.Name = "诊疗卡";
                    break;
                case 1:
                    _cardType.Name = "健康卡";
                    break;
                default:
                    _cardType.Name = "其他";
                    break;
            }
            return _cardType;
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult BlackList_Create([DataSourceRequest] DataSourceRequest request, BlackListViewModel black)
        {
            if (black != null && ModelState.IsValid)
            {
                WxBlackList dbBlackList = new WxBlackList
                {
                  CardType = black.CardType.Id,
                  PatientName = black.PatientName,
                  CardNo = black.CardNo,
                  CancelCount= black.CancelCount,
                  CancelMonth = black.CancelMonth,
                  CancelYear = black.CancelYear,
                  IdenNo = black.IdenNo,
                  Phone = black.Phone,
                  CreateDT = DateTime.Now
                };
                _ctx.WxBlackLists.Add(dbBlackList);
                _ctx.SaveChanges();
                black.Id = dbBlackList.Id;
            }

            return Json(new[] { black }.ToDataSourceResult(request, ModelState));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult BlackList_Update([DataSourceRequest] DataSourceRequest request, BlackListViewModel black)
        {
            if (black != null && ModelState.IsValid)
            {
                var dbBlack = _ctx.WxBlackLists.FirstOrDefault(x => x.Id == black.Id);
                if (dbBlack != null)
                {
                    dbBlack.CardType = black.CardType.Id;
                    dbBlack.PatientName = black.PatientName;
                    dbBlack.CardNo = black.CardNo;
                    dbBlack.CancelCount = black.CancelCount;
                    dbBlack.CancelMonth = black.CancelMonth;
                    dbBlack.CancelYear = black.CancelYear;
                    dbBlack.IdenNo = black.IdenNo;
                    dbBlack.Phone = black.Phone;
                    dbBlack.LastDT = DateTime.Now;
                    _ctx.SaveChanges();
                }
            }

            return Json(new[] { black }.ToDataSourceResult(request, ModelState));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult BlackList_Destroy([DataSourceRequest] DataSourceRequest request, BlackListViewModel black)
        {
            if (black != null)
            {
                var dbBlack = _ctx.WxBlackLists.FirstOrDefault(x => x.Id == black.Id);
                if (dbBlack != null)
                {
                    _ctx.WxBlackLists.Remove(dbBlack);
                    _ctx.SaveChanges();
                }
            }

            return Json(new[] { black }.ToDataSourceResult(request, ModelState));
        }
        #endregion

        #region 当月运营报表

        public ActionResult HistoryChartData()
        {
            var startDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            var endDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 1);

            //var startDate = new DateTime(2014, 6, 1);
            //var endDate = new DateTime(2014, 6, 30);
            var list = new List<ChartViewModel>();
            #region Mysql
            List<GetStatisticReprotModel> model = _ctx.ExecuteStoredProcedure<GetStatisticReprotModel>("GetStatisticReport", startDate,endDate);
            model.Each(x =>
            {
                list.Add(new ChartViewModel
                {
                    Day = x.MonthDay.ToString("yyyy_MM-dd"),
                    LineType = x.LineType,
                    EnergyValue = x.Amount
                });
            });
            #endregion
            #region Sqlserver
            //var apptRecord =
            //    _ctx.ApptOrders.Where(t => t.OrderStatus == 21 && t.CreateTime > startDate && t.CreateTime <= endDate)
            //        .GroupBy(
            //            x =>
            //                SqlFunctions.DateName("yyyy", x.CreateTime) + SqlFunctions.DateName("mm", x.CreateTime) +
            //                SqlFunctions.DateName("dd", x.CreateTime)).Select(x =>
            //                    new
            //                    {
            //                        RecordDay = x.Key,
            //                        Value = x.Sum(y => y.SumFee)
            //                    }).ToList();
            //var billRecord =
            //    _ctx.BillOrders.Where(t => t.OrderStatus == 8 && t.CreateTime > startDate && t.CreateTime <= endDate)
            //        .GroupBy(
            //            x =>
            //                SqlFunctions.DateName("yyyy", x.CreateTime) + SqlFunctions.DateName("mm", x.CreateTime) +
            //                 SqlFunctions.DateName("dd", x.CreateTime)).Select(x =>
            //                    new
            //                    {
            //                        RecordDay = x.Key,
            //                        Value = x.Sum(y => y.PrescMoney)
            //                    }).ToList();
            //var prepayRecord =
            //    _ctx.InpatientPrepayOrders.Where(
            //        t => t.OrderStatus == 8 && t.CreateTime > startDate && t.CreateTime <= endDate)
            //        .GroupBy(
            //            x =>
            //                SqlFunctions.DateName("yyyy", x.CreateTime) + SqlFunctions.DateName("mm", x.CreateTime) +
            //                SqlFunctions.DateName("dd", x.CreateTime)).Select(x =>
            //                    new
            //                    {
            //                        RecordDay = x.Key,
            //                        Value = x.Sum(y => y.PrepayMoney)
            //                    }).ToList();

            //var dinnerRecord =
            //    _ctx.DinnerOrders.Where(t => t.OrderStatus == 6 && t.CreateTime > startDate && t.CreateTime <= endDate)
            //        .GroupBy(
            //            x =>
            //                SqlFunctions.DateName("yyyy", x.CreateTime) + SqlFunctions.DateName("mm", x.CreateTime) +
            //                SqlFunctions.DateName("dd", x.CreateTime)).Select(x =>
            //                    new
            //                    {
            //                        RecordDay = x.Key,
            //                        Value = x.Sum(y => y.TotalMoney)
            //                    }).ToList();
            ////得到所有的日期和时间段
            //var list1 = apptRecord.Select(x => new
            //{
            //    RecordDay = x.RecordDay.Length == 7 ? x.RecordDay.Insert(6, "0") : x.RecordDay
            //}).Union(billRecord.Select(x => new {RecordDay = x.RecordDay.Length == 7 ? x.RecordDay.Insert(6, "0") : x.RecordDay }))
            //    .Union(prepayRecord.Select(x => new {RecordDay = x.RecordDay.Length == 7 ? x.RecordDay.Insert(6, "0") : x.RecordDay }))
            //    .Union(dinnerRecord.Select(x => new {RecordDay = x.RecordDay.Length == 7 ? x.RecordDay.Insert(6, "0") : x.RecordDay }))
            //    .ToList();

            //apptRecord.ForEach(x =>
            //{
            //    list.Add(new ChartViewModel
            //    {
            //        Day = x.RecordDay.Length ==7 ? x.RecordDay.Insert(6,"0") : x.RecordDay,
            //        LineType = "预约挂号",
            //        EnergyValue = x.Value
            //    });
            //});

            //billRecord.ForEach(x =>
            //{
            //    list.Add(new ChartViewModel
            //    {
            //        Day = x.RecordDay.Length == 7 ? x.RecordDay.Insert(6, "0") : x.RecordDay,
            //        LineType = "缴费",
            //        EnergyValue = x.Value
            //    });
            //});

            //prepayRecord.ForEach(x =>
            //{
            //    list.Add(new ChartViewModel
            //    {
            //        Day = x.RecordDay.Length == 7 ? x.RecordDay.Insert(6, "0") : x.RecordDay,
            //        LineType = "预缴金",
            //        EnergyValue = x.Value
            //    });
            //});

            //dinnerRecord.ForEach(x =>
            //{
            //    list.Add(new ChartViewModel
            //    {
            //        Day = x.RecordDay.Length == 7 ? x.RecordDay.Insert(6, "0") : x.RecordDay,
            //        LineType = "订餐",
            //        EnergyValue = x.Value
            //    });
            //});

            ////拼凑Null
            //list1.ForEach(x =>
            //{
            //    if (!list.Any(y => y.Day == x.RecordDay && y.LineType == "预约挂号"))
            //    {
            //        list.Add(new ChartViewModel
            //        {
            //            Day = x.RecordDay,
            //            LineType = "预约挂号",
            //            EnergyValue = null,
            //        });
            //    }

            //    if (!list.Any(y => y.Day == x.RecordDay && y.LineType == "缴费"))
            //    {
            //        list.Add(new ChartViewModel
            //        {
            //            Day = x.RecordDay,
            //            LineType = "缴费",
            //            EnergyValue = null,
            //        });
            //    }
            //    if (!list.Any(y => y.Day == x.RecordDay && y.LineType == "预缴金"))
            //    {
            //        list.Add(new ChartViewModel
            //        {
            //            Day = x.RecordDay,
            //            LineType = "预缴金",
            //            EnergyValue = null,
            //        });
            //    }

            //    if (!list.Any(y => y.Day == x.RecordDay && y.LineType == "订餐"))
            //    {
            //        list.Add(new ChartViewModel
            //        {
            //            Day = x.RecordDay,
            //            LineType = "订餐",
            //            EnergyValue = null,
            //        });
            //    }
            //});
            #endregion
            return Json(list, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region 导出报表
        [HttpPost]
        public ActionResult Excel_Export_Save(string contentType, string base64, string fileName)
        {
            var fileContents = Convert.FromBase64String(base64);

            return File(fileContents, contentType, fileName);
        }
        #endregion


    }
}